import React, { Component } from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import './style.css'
class Layout extends Component {

  constructor(props) {
    super(props);
    this.online = false;
    this.sendMessage = this.sendMessage.bind(this)
    this.handleTextChange = this.handleTextChange.bind(this)
    this.handleNameChange = this.handleNameChange.bind(this)
    this.initWebSocket = this.initWebSocket.bind(this)
    this.intervalFun = this.intervalFun.bind(this)
    this.message = ''
    this.name = 'admin';
    this.socket = new Object();

  }

  intervalFun(){
    if(!this.online){
        this.initWebSocket()
      }
  }

  initWebSocket(){
    let that = this;
    this.socket = new WebSocket('ws://10.11.27.31:8080/ws?name=' + this.name)
    // this.socket.timout = 60000;
    this.socket.ontimeout = function(event){
        console.log('timeout' + event)
    }
    // 监听消息
    this.socket.onmessage = function(event) {
      console.log('Client received a message',event);
      let div = document.createElement("div");
      div.className = 'message-list'
      div.innerHTML = event.data
      let box = document.getElementById('message-box');
      box.appendChild(div);
      box.scrollTop = box.scrollHeight
    }
    // 监听Socket的关闭
    this.socket.onclose = function(event) { 
      console.log('Client notified socket has closed',event); 
      event.target.send(that.name + '下线了!!')
      that.online = false;
    }
    // 关闭Socket.... 
    this.socket.onerror = function(event){
      console.error('client error',event)
      event.target.close()
      that.online = false;
    } 
    // 打开Socket 
    this.socket.onopen = function(event) { 
      that.online = true
      // event.target.send( that.name + '上线了!!')
    }
  }

  handleTextChange(event){
    this.message = event.target.value
  }
  handleNameChange(event){
    this.name = event.target.value
    this.socket.close()
  }

  componentWillMount(){
    setInterval(this.intervalFun,3000);
  }



  sendMessage(event){
    console.log(this.message)
    this.socket.send(this.message)
  }

  render() {
    return (
      <div  style={{ marginTop: '20px', backgroundColor: '#fff' }}>
        <div id='message-box'>
        </div>
        <div className='message-input' >
          name:<input style={{width:'50%',height:'60px',border: '1px solid'}} onChange={this.handleNameChange}/>            
          <input id='message-text' onChange={this.handleTextChange}/>            
          <button style={{height:'100px',width:'15%'}} onClick={this.sendMessage}>发送</button>
        </div>
      </div>
    )
  }
}

export default connect()(Layout);
